// pages/index/index.js
const request = require('../../utils/request.js');
Page({
  data: {
    helpId: 53, // 需要请求的 helpId
    details: {
      distance: 0,
      latitude: 12.2,
      title: "你好",
      content: "内容1",
      principalAmount: 30,
      statement: 6,
      id: 44,
      longitude: 11.1,
      depositAmount: 40,
      averageAmount: 4.0,
      actualAmount: 12.0,
      totalAmount: 90.0,
      commisionAmount: 32,
      location: "天马学生公寓",
      bountyAmount: 20
    }, // 存储返回的详细信息
    seeker:{
      head: '/head/oPi0m7eCbG5LZgIylkT11kR06BXg/FC3FEC12AC54CAE0802EFEF370CD82E8.jpg',
      seekerRating: 4.5,
      helperRating: -1.0,
      name: "臭屁"
    },
    helper:{
      head: "/head/oPi0m7eCbG5LZgIylkT11kR06BXg/FC3FEC12AC54CAE0802EFEF370CD82E8.jpg",
      seekerRating: -1.0,
      helperRating: 3.0,
      name: "臭屁1"
    },
    latitude: 28.174943,
    longitude: 112.946006,
    location:'湖大信科院',
    phone: '010-1478965',
    role: 1,
    status: '未到达',
    markers: [],
    polyline: [],
    order: {},
  },
  fetchHelpDetails: function() {
    const that = this;
    const helpId=that.data.helpId
    wx.showLoading({
      title: '加载中...',
    });

    // 发送 GET 请求到 /help/details 接口
    request.request('/help/details', 'GET', { helpId: helpId })
      .then(res => {
        if (res.code === "200") {
          console.log( res.data)
          // 请求成功，更新页面数据
          this.setData({
            details: res.data.detail || {},
            seeker:res.data.seekerInfo||{},
            helper:res.data.helperInfo||{},

            loading: false,
          });
          if (
            this.data.seeker && this.data.helper && 
            this.data.seeker.location && this.data.helper.location && 
            this.data.seeker.location.latitude && this.data.seeker.location.longitude && 
            this.data.helper.location.latitude && this.data.helper.location.longitude
          ) {
            const seekerLocation={
              latitude:this.data.seeker.location.latitude,
              longitude:this.data.seeker.location.longitude
            }
            const helperLocation={
              latitude:this.data.helper.location.latitude,
              longitude:this.data.helper.location.longitude
            }
            // 如果seeker和helper的位置信息都存在且latitude和longitude不为空，执行以下代码
            if(this.data.role==0){
              this.setData({
                          markers: this.getMarkers(
                seekerLocation.latitude, 
                seekerLocation.longitude, 
                helperLocation.latitude, 
                helperLocation.longitude
              )    
              })

            }else{
              this.setData({
                markers: this.getMarkers(
      helperLocation.latitude, 
      helperLocation.longitude,
       seekerLocation.latitude, 
      seekerLocation.longitude, 
    )    
    })
            }
            this.setData({
              polyline: this.getPolyline(
                seekerLocation.latitude, 
                seekerLocation.longitude, 
                helperLocation.latitude, 
                helperLocation.longitude
              )
            });
          } else {
            if(this.data.role==1){
              this.setData({
                markers: this.getMarkers(
                  this.data.latitude, 
                  this.data.longitude, 
                  this.data.details.latitude, 
                  this.data.details.longitude
                ),
                polyline: this.getPolyline(
                  this.data.latitude, 
                  this.data.longitude, 
                  this.data.details.latitude, 
                  this.data.details.longitude
                )
              });
            }else{
              this.setData({
                markers: [
                  {
                      id: 1,
                      latitude: this.data.latitude,
                      longitude: this.data.longitude,
                      iconPath: 'http://106.52.12.104:8080/image'+this.data.helper.head, // 自定义图标
                      width: 30,
                      height: 30,
                      label: {
                          content: '我的位置',
                          color: '#000',
                          fontSize: 14,
                          anchorX: -20,
                          anchorY: -40
                      }
                  }
              ]
              });
            }
          }
        } else {
          // 请求返回错误码，显示错误信息
          that.setData({
            error: res.message,
            loading: false
          });
          wx.showToast({
            title: res.message || '请求失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        // 请求失败，显示错误信息
        that.setData({
          error: '网络请求失败',
          loading: false
        });
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },
  onLoad(options) {
    const helpId =options.id;
    const role=options.role;
    this.setData({
      role: role,
      helpId:helpId
    });
    //this.fetchHelpDetails(helpId);
    this.startLocationUpdates();
   
  },
  onUnload() {
    // 页面卸载时停止定时器
    this.stopLocationUpdates();
},
startLocationUpdates() {
  wx.getSetting({
    success: res => {
      if (!res.authSetting['scope.userLocation']) {
        // 未授权，提示用户授权
        wx.authorize({
          scope: 'scope.userLocation',
          success: () => {
            // 用户同意授权
              this.getUserLocation();
          },
          fail: () => {
            // 用户拒绝授权，打开设置页面让用户手动授权
            wx.showModal({
              title: '需要授权',
              content: '需要获取您的地理位置权限以展示地图功能',
              success: modalRes => {
                if (modalRes.confirm) {
                  wx.openSetting({
                    success: settingRes => {
                      if (settingRes.authSetting['scope.userLocation']) {
                        // 用户已授权
                          this.getUserLocation();
                      }
                    }
                  });
                }
              }
            });
          }
        });
      } else {
        // 已授权，直接获取用户位置
          this.getUserLocation();
      }
    }
  });
  this.fetchHelpDetails(); // 先获取一次数据
  this.locationTimer = setInterval(() => {
          this.getUserLocation();
    this.fetchHelpDetails();
  }, 60 * 1000); // 每分钟调用一次
},
stopLocationUpdates() {
  if (this.locationTimer) {
      clearInterval(this.locationTimer);
  }
},
  uploadLocation() {
    request.request(
      '/help/nowLocation',
     'POST',
       {
        longitude:this.data.longitude,
        latitude:this.data.latitude,
        location:this.data.location
      }).then(response => {
      // 成功处理返回结果
      const { code, message, data, timestamp } = response;
      if (code === '200') {
console.log("位置上传成功")
      } else {
          wx.showToast({
              title: '位置上传错误',
              icon: 'none'
          });
      }
  }).catch(error => {
      // 错误处理
      console.error('请求出错:', error);
      wx.showToast({
          title: '网络请求失败，请稍后重试',
          icon: 'none'
      });
  });
},
  getUserLocation() {
    wx.getLocation({
      type: 'wgs84',
      success: res => {
        const { latitude, longitude } = res;
        this.setData({
          latitude,
          longitude,
        });
     // 调用逆地理编码获取位置名称
       this.getLocationName(latitude, longitude);
      }
    });
  },
  // 逆地理编码获取位置名称+上传地址
getLocationName(latitude, longitude) {
  // 你需要替换为你的腾讯地图密钥
  const key = 'N6MBZ-KXEEN-DR5F6-SRJK4-XNTH6-T3BX4'; 
  wx.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}`,
      method: 'GET',
      success: res => {
          if (res.data.status === 0) {
              const locationName = res.data.result.formatted_addresses.recommend; // 获取推荐地址
              this.setData({
                  location:locationName // 将位置名称保存到数据中
              });
              // 你可以在这里处理获取到的地址信息，比如上传到服务器
              this.uploadLocation();
              console.log('位置名称:', locationName);
          } else {
              console.error('地址获取失败:', res.data.message);
          }
      },
      fail: err => {
          console.error('请求地址信息失败:', err);
      }
  });
},
getMarkers(myLat, myLng, friendLat, friendLng) {
  return [
      {
          id: 1,
          latitude: myLat,
          longitude: myLng,
          iconPath: 'http://106.52.12.104:8080/image'+this.data.helper.head, // 自定义图标
          width: 30,
          height: 30,
          label: {
              content: '我的位置',
              color: '#000',
              fontSize: 14,
              anchorX: -20,
              anchorY: -40
          }
      },
      {
          id: 2,
          latitude: friendLat,
          longitude: friendLng,
          iconPath: 'http://106.52.12.104:8080/image'+this.data.seeker.head, // 自定义图标
          width: 30,
          height: 30,
          label: {
              content: '对方位置',
              color: '#000',
              fontSize: 14,
              anchorX: -20,
              anchorY: -40
          }
      }
  ];
},

// 获取路线数组
getPolyline(myLat, myLng, friendLat, friendLng) {
  return [{
      points: [{
          latitude: myLat,
          longitude: myLng
      }, {
          latitude: friendLat,
          longitude: friendLng
      }],
      color: "#FF0000DD",
      width: 4,
      dottedLine: false
  }];
},
  onConfirm:function() {
    // 准备请求参数
    const params = {
        id: this.data.details.id,  // 这里你可以动态获取 id 或者从其他地方传递进来
        commision_amount:this.data.details.commisionAmount
    };

    // 发送 POST 请求
   request.request(
        '/help/settle',
         'POST',
        params,
    ).then(response => {
        // 成功处理返回结果
        const { code, message, data, timestamp } = response;
        if (code === '200') {
            wx.showToast({
                title: "订单完成",  // 显示结算成功信息
                icon: 'success'
            });
            wx.redirectTo({
              url: '/subpackages/mine-module/pages/my_order/my_order',
            })
            // 你可以在这里做一些其他操作，比如更新页面数据或者跳转
        } else {
            wx.showToast({
                title: message || '结算失败',
                icon: 'none'
            });
        }
    }).catch(error => {
        // 错误处理
        console.error('请求出错:', error);
        wx.showToast({
            title: '网络请求失败，请稍后重试',
            icon: 'none'
        });
    });
  },
   onArrive:function() {
    // 准备请求参数

    // 发送 GET 请求
    request.request(
         '/help/arrived',
         'GET',
         {
            helpId: this.data.details.id  // 设置 GET 请求参数
         }
    ).then(response => {
        // 成功处理返回结果
        const { code, message, data, timestamp } = response;
        if (code === '200') {
            wx.showToast({
                title: '已到达目的地',  // 显示成功信息
                icon: 'success'
            });
            this.fetchHelpDetails();
            // 你可以在这里做一些其他操作，比如更新页面状态、数据或者跳转
        } else {
            wx.showToast({
                title: message || '请求失败',
                icon: 'none'
            });
        }
    }).catch(error => {
        // 错误处理
        console.error('请求出错:', error);
        wx.showToast({
            title: '网络请求失败，请稍后重试',
            icon: 'none'
        });
    });
},
  // Call function for "报警"
  alertOn() {
    wx.makePhoneCall({
      phoneNumber: '110', // Use appropriate emergency number
      fail() {
        wx.showToast({
          title: '拨号失败',
          icon: 'none'
        });
      }
    });
  },

  // Call function for "打电话"
  phoneOn() {
    wx.makePhoneCall({
      phoneNumber: '1234567890', // Example number
      fail() {
        wx.showToast({
          title: '拨号失败',
          icon: 'none'
        });
      }
    });
  },

  // Navigation function for "发信息"
  sendMessage() {
        let id = '';
    let chatname= '';
    if(this.data.role){
      id=this.data.details.userId;
      chatname=this.data.seeker.name;
    }else{
      id=this.data.details.helperId;
      chatname=this.data.helper.name;
    }
    wx.redirectTo({
      url: `/subpackages/message-module/pages/chat-room/chat-room?id=${id}&name=${chatname}` // Path to the tab page
    });
  },

  // Confirmation dialog for "取消订单"
  cancelOrder() {
    wx.showModal({
      title: '取消订单',
      content: '确定要取消订单吗？',
      success: (res) => { // Using arrow function
        if (res.confirm) {
          this.onCancelTask();  // `this` is correctly preserved here
        } else if (res.cancel) {
          wx.showToast({
            title: '取消操作',
            icon: 'none'
          });
        }
      }
    });
  },
  
  // Define onCancelTask as a regular function
  onCancelTask() {
    request.request('/resort/cancelHelp', 'GET', {
      helpID: this.data.helpId,
    })
    .then(res => {
      if (res.code === "200") {
        console.log("取消订单");
        wx.navigateTo({
          url: '/subpackages/mine-module/pages/my_order/my_order',
        });
      } else {
        wx.showToast({
          title: '参数错误',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      console.error(err);
      wx.showToast({
        title: '请求失败',
        icon: 'none'
      });
    });
  }
  
});
